<?php

/**
 * Server_Api_Share
 * 分享服务
 * Author: netman
 * DateTime:  2023/9/11 16:37
 */
class Service_Api_Share extends Contract_Api_Share
{

    use Trait_Api_Common;
    use Trait_Api_Image;
    use Trait_Api_Response;
    use Trait_Api_Distributor;

    public function __construct()
    {
    }

    /**
     * 普通分享
     * @param array $params
     * @return array
     * User: netman
     * Date: 2023/9/27 14:37
     */
    function share_wx_info(array $params): array
    {
        $config = Model_Share_Weixin::get_config();
        $url    = $params['url'];
        $ticket = Model_Share_Weixin::get_ticket($config['appid'], $config['appsecret']);
        if (!$ticket) {
            throw new Exception('ticket获取失败');
        }
        $noncestr  = Model_Share_Weixin::get_wx_noncestr();
        $timestamp = time();
        //签名URL只需要#前面部分
        $sign_url =   substr($url,0,strpos($url,'#'));
        $queryArr  = array('jsapi_ticket' => $ticket, 'noncestr' => $noncestr, 'timestamp' => $timestamp, 'url' => $sign_url);
        $queryStr  = '';
        foreach ($queryArr as $k => $v) {
            $queryStr .= $k . '=' . $v . '&';
        }
        $queryStr  = substr($queryStr, 0, -1);
        $signature = sha1($queryStr);
        //  站点基础信息
        $web_basc_info = Model_Share_Weixin::get_wx_share_default_info();

        //如果是拼团分享
        if (stripos($url, 'groupbooking')) {
            $together_join_id = substr($url, stripos($url, '?id=') + 4, strlen($url));
            $together_join    = DB::select('status')
                ->from('together_join')
                ->where('id', '=', $together_join_id)
                ->execute()
                ->current();
            if ($together_join['status'] == 2) {
                $web_basc_info['title'] = Model_Sysconfig::get_sys_conf('value', 'cfg_together_success_content');
            } else {
                $web_basc_info['title'] = Model_Sysconfig::get_sys_conf('value', 'cfg_together_start_content');
            }
            $web_basc_info['desc'] = $web_basc_info['title'];
        }
        $wx_data = array(
            'appid' => $config['appid'],
            'ticket' => $ticket,
            'noncestr' => $noncestr,
            'timestamp' => $timestamp,
            'signature' => $signature,
            'url' => $url,
            'default' => $web_basc_info,
        );
        return $wx_data;
    }

    /**
     * 微信分销商分享
     * @param array $params
     * @return array
     * User: netman
     * Date: 2023/9/27 14:38
     */
    function share_wx_fenxiao_info(array $params): array
    {
        $url     = $params['url'];
        $type_id = $params['type_id'];

        $cfg_wx_appid     = Model_Fenxiao_Config::get_val('cfg_fenxiao_wx_appid');
        $cfg_wx_appsecret = Model_Fenxiao_Config::get_val('cfg_fenxiao_wx_appsecret');
        if (!$cfg_wx_appid && !$cfg_wx_appsecret) {
            $config           = Model_Share_Weixin::get_config();
            $cfg_wx_appid     = $config['appid'];
            $cfg_wx_appsecret = $config['appsecret'];
        }
        $default_litpic      = Model_Fenxiao_Config::get_val('cfg_fenxiao_weixin_other_litpic');
        $default_title       = Model_Fenxiao_Config::get_val('cfg_fenxiao_weixin_other_title');
        $default_description = Model_Fenxiao_Config::get_val('cfg_fenxiao_weixin_other_description');
        $default_litpic      = !empty($default_litpic) ? $this->img_url($default_litpic) : '';
        $ticket              = Model_Share_Weixin::get_ticket($cfg_wx_appid, $cfg_wx_appsecret);
        if (!$ticket) {
            throw new Exception('ticket获取失败');
        }
        $noncestr  = Model_Share_Weixin::get_wx_noncestr();
        $timestamp = time();
        //签名URL只需要#前面部分
        $sign_url =   substr($url,0,strpos($url,'#'));
        $queryArr = array('jsapi_ticket' => $ticket, 'noncestr' => $noncestr, 'timestamp' => $timestamp, 'url' => $sign_url);
        $queryStr = '';
        foreach ($queryArr as $k => $v) {
            $queryStr .= $k . '=' . $v . '&';
        }
        $queryStr  = substr($queryStr, 0, -1);
        $signature = sha1($queryStr);
        //去掉fxpcode
        if(stripos($url,'&amp;fxpcode')){
            $index = stripos($url,'&amp;fxpcode');
            $url = substr($url,0,$index);
        }

        $data      = array(
            'appid' => $cfg_wx_appid,
            'ticket' => $ticket,
            'noncestr' => $noncestr,
            'timestamp' => $timestamp,
            'signature' => $signature,
            'url' => $url,
            'default' => array(
                'title' => $default_title,
                'desc' => $default_description,
                'litpic' => $default_litpic,
            )
        );

        // 产品类型分享 分享秒杀产品显示产品标题 分享红包
        if ($type_id || stripos($url, 'sales') || stripos($url, 'redEnvelope')) {
            $fenxiao       = $this->check_member_distribution($params['mid']);
            $product_title = Model_Fenxiao_Config::get_val('cfg_fenxiao_weixin_title'); // 分享产品详情页
            $title         = $params['title'];
            $desc          = $params['desc'];
            $litpic        = $params['litpic'];
            $price         = $params['price'];
            $replace_arr   = array(
                'TITLE' => $title,
                'PRICE' => $price,
                'SELLPOINT' => $desc
            );
            foreach ($replace_arr as $key => $val) {
                $product_title = str_replace('{#' . $key . '#}', $val, $product_title);
            }
            if ($type_id == 4) {
                $litpic = $default_litpic;
            }
            //红包单独配置
            if (stripos($url, 'redEnvelope')) {
                $arr['title'] = $title;
            } else {
                $arr['title'] = $product_title ? $product_title : $default_title;
            }

            $arr['desc']     = $desc;
            $arr['litpic']   = $litpic ? $litpic : $default_litpic;
            $arr['fxcode']   = $fenxiao['fxcode'];
            $data['default'] = $arr;
            $data['url']     = $data['url'] . '&fxpcode=' . $fenxiao['fxcode'];
        }

        //如果是拼团分享
        if (stripos($url, 'groupbooking/detail')) {
            $together_join_id = substr($url, stripos($url, '?id=') + 4, strlen($url));
            $together_join    = DB::select('status')
                ->from('together_join')
                ->where('id', '=', $together_join_id)
                ->execute()
                ->current();
            if ($together_join['status'] == 2) {
                $desc = Model_Sysconfig::get_sys_conf('value', 'cfg_together_success_content');
            } else {
                $desc = Model_Sysconfig::get_sys_conf('value', 'cfg_together_start_content');
            }
            $data['default']['desc']   = $desc;
            $data['default']['litpic'] = $params['litpic'] ?? '';
        }
        return $data;
    }

    /**
     * 微信小程序分享
     * @param array $params
     * @return array
     * User: netman
     * Date: 2023/9/27 14:38
     */
    function share_mp_info(array $params): array
    {
        $fenxiao = false;
        // 分销商分享
        $title      = $params['title'];
        $price      = $params['price'] ? $params['price'] : '';
        $sellpoint  = $params['sellpoint'] ? $params['sellpoint'] : '';
        $share_type = $params['share_type'] ? $params['share_type'] : '';

        $data = array(
            'title' => $title,
            'litpic' => '',
            'desc' => $sellpoint,
        );
        // 检查是否是分销商
        if (St_Functions::is_normal_app_install('mobiledistribution')) {
            if ($params['mid']) {
                $fenxiao = $this->check_member_distribution($params['mid']);
            }
        }
        // 获取不同类型分销的基础配置
        if (isset($fenxiao['isfenxiao']) && $fenxiao['isfenxiao']) { // 分销商模式分享
            $default_title       = Model_Fenxiao_Config::get_val('cfg_fenxiao_weixin_other_title');
            $product_title       = Model_Fenxiao_Config::get_val('cfg_fenxiao_weixin_title'); // 分享产品详情页
            $default_description = Model_Fenxiao_Config::get_val('cfg_fenxiao_weixin_other_description');
            $default_litpic      = Model_Fenxiao_Config::get_val('cfg_fenxiao_weixin_other_litpic');
            $cfg_m_logo          = Model_Sysconfig::get_configs(0, 'cfg_m_logo', 1);
            $default_litpic      = !empty($default_litpic) ? $this->img_url($default_litpic) : $this->img_url($cfg_m_logo); // 若不设置，则默认显示网站手机端logo
            $data                = array(
                'title' => $default_title,
                'litpic' => $default_litpic,
                'desc' => $default_description,
            );

            // 产品类型分享
            if ($share_type == 1) {
                $replace_arr = array(
                    'TITLE' => $title,
                    'PRICE' => $price,
                    'SELLPOINT' => $sellpoint
                );
                foreach ($replace_arr as $key => $val) {
                    $product_title = str_replace('{#' . $key . '#}', $val, $product_title);
                }
                $data['title']  = $product_title;
                $data['desc']   = $sellpoint;
                $data['fxcode'] = $fenxiao['fxcode'];
            }
        } else { // 普通模式分享
            if (St_Functions::is_normal_app_install('share_wx_client')) {
                $data = Model_Share_Weixin::get_wx_share_default_info();
                if ($title) {
                    $data['title'] = $title;
                }
                if ($sellpoint) {
                    $data['desc'] = $sellpoint;
                }
            }
        }
        return $data;
    }


}